package com.sprocomm.agingtest.reboot;

import com.sprocomm.agingtest.BaseActivity;
import com.sprocomm.agingtest.Config;
import com.sprocomm.agingtest.R;
import com.sprocomm.agingtest.Tools;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.PowerManager;
import android.provider.Settings;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class RebootTest extends BaseActivity {
    private TextView tvBT, tvGPS;
    private Button btnStart,btnStop;

    /**
     * 测试的结果
     */
    private boolean BT_RESULT = true;
    private boolean GPS_RESULT = true;
    /**
     * 是否有测试设备
     */
    private boolean havaBT = true;
    private boolean havaGPS = true;
    private SharedPreferences mSharedPreferences;
    private long mStartTime;
    private long mEndTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reboot_test);
        mSharedPreferences = this.getSharedPreferences("reboot", MODE_PRIVATE);

        mStartTime = mSharedPreferences.getLong("startTime", System.currentTimeMillis());
        mEndTime = mSharedPreferences.getLong("endTime", System.currentTimeMillis());

        initViews();
        Intent i = getIntent();
        boolean isManual = i.getBooleanExtra("isManual", false);
        Tools.logE("isManual:" + isManual);

        checkBTGPS();//检查硬件是否支持

        if (isManual) {
            btnStart.setEnabled(true);
            //判断如果手动模式进来的时候是正在测试，那么说明重启之后没有唤醒程序，判定fail
            if (getTestMode()){
                setTestMode(false);
                btnStart.setEnabled(false);
                btnStop.setEnabled(false);
                btnStart.setText("Please fail test");
            }
        } else {
            btnStart.setEnabled(false);
            Tools.logE("mEndTime:"+mEndTime+"currentTimeMillis:"+System.currentTimeMillis());
            if (mEndTime < System.currentTimeMillis()) {
                //测试通过
                btnStart.setText("PASS");
                btnStop.setEnabled(false);
                mSharedPreferences.edit().clear().commit();
                setPassBtnEnable(true);
            }else {
                doBTTest();
            }
        }
    }

    private void openGPS() {
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean isOn = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (isOn) {
            // GPS on
            Tools.logE("GPS is ON");
            updateUI(tvGPS, "GPS is ON");
        } else {
            //GPS off
            //Settings.Secure.setLocationProviderEnabled(getContentResolver(),LocationManager.GPS_PROVIDER, true);
            boolean ok = Settings.Secure.putInt(getContentResolver(),
                    Settings.Secure.LOCATION_MODE,
                    Settings.Secure.LOCATION_MODE_HIGH_ACCURACY);
            if (ok) {
                //GPS打开成功
                Tools.logE("GPS打开成功");
                updateUI(tvGPS, "GPS open  success");
            } else {
                //GPS打开失败
                Tools.logE("GPS打开失败");
                updateUI(tvGPS, "GPS open fail");
                GPS_RESULT = false;
                btnStart.setEnabled(false);
                btnStart.setText("FAIL");
            }

        }

    }

    private void closeGPS() {
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean isOn = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (isOn) {
            //GPS是打开的
            boolean ok = Settings.Secure.putInt(getContentResolver(),
                    Settings.Secure.LOCATION_MODE,
                    Settings.Secure.LOCATION_MODE_OFF);
            if (ok) {
                //GPS成功关闭
                Tools.logE("GPS成功关闭");
                updateUI(tvGPS, "GPS closed success");
            } else {
                //GPS关闭失败，判定fail
                Tools.logE("GPS关闭失败，判定fail");
                updateUI(tvGPS, "GPS closed fail");

                GPS_RESULT = false;
                btnStart.setEnabled(false);
                btnStart.setText("FAIL");
            }
        } else {
            //GPS是关闭的
            Tools.logE("GPS是关闭的");
            updateUI(tvGPS, "GPS is OFF");
        }
    }

    private void reboot() {
        if (!getTestMode()){
            Tools.logE("取消reboot测试");
            updateBtnUI(btnStop,"Pls exit test");
            return;
        }
        if (GPS_RESULT && BT_RESULT) {
            Tools.logE("reboot()");
            PowerManager p = (PowerManager) getSystemService(POWER_SERVICE);
            if (p != null) {
                p.reboot("Agint Test Nedd Reboot");
            } else {

            }
        } else {
            //测试已经fail
            updateUI(btnStop,"Pls fail  test");

        }

    }

    private void initViews() {
        tvBT = (TextView) findViewById(R.id.tv_show_bt);
        tvGPS = (TextView) findViewById(R.id.tv_show_gps);
        btnStart = (Button) findViewById(R.id.btn_start);
        btnStop = (Button) findViewById(R.id.btn_stop);

    }

    public void start(View view) {
        setStartEndTime();
        setTestMode(true);
        doBTTest();
        btnStart.setEnabled(false);
        btnStop.setEnabled(true);
    }

    /**
     * 设置测试开始的时间
     * 并计算出测试结束的时间
     */
    private void setStartEndTime() {
        mStartTime = System.currentTimeMillis();
        mEndTime = mStartTime + Config.REBOOT_TEST_TIME;
        mSharedPreferences.edit().putLong("startTime", mStartTime).commit();
        mSharedPreferences.edit().putLong("endTime", mEndTime).commit();
    }

    @Override
    protected void onDestroy() {
        Tools.logE("reboot-onDestroy");
        setTestMode(false);
        super.onDestroy();
    }

    private void doGPSTest() {
        if (!havaGPS) {
            Tools.logE("没有GPS设备");
            updateUI(tvGPS, "GPS is not supported");
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    openGPS();
                    Thread.sleep(2000);
                    closeGPS();
                    Thread.sleep(2000);
                    reboot();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }


    private void doBTTest() {
        if (!havaBT) {
            Tools.logE("没有BT设备");
            updateUI(tvBT, "Bluetooth is not supported");
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    openBT();
                    Thread.sleep(2000);
                    closeBT();
                    Thread.sleep(2000);
                    doGPSTest();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }

    private void openBT() {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter.isEnabled()) {
            //蓝牙打开
            Tools.logE("BT is ON");
            updateUI(tvBT, "BT is ON ");
        } else {
            boolean ok = adapter.enable();
            if (ok) {
                //蓝牙打开
                Tools.logE("BT打开成功");
                updateUI(tvBT, "BT open success ");
            } else {
                //蓝牙打开失败
                Tools.logE("BT打开失败");
                updateUI(tvBT, "BT open fail ");
                btnStart.setEnabled(false);
                btnStart.setText("FAIL");
                BT_RESULT = false;
            }
        }
    }

    private void closeBT() {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter.isEnabled()) {
            boolean ok = adapter.disable();
            if (ok) {
                //关闭成功
                Tools.logE("BT closed success");
                updateUI(tvBT, "BT closed success ");

            } else {
                //关闭失败
                Tools.logE("BT-close-fail");
                updateUI(tvBT, "BT closed fail ");
                btnStart.setEnabled(false);
                btnStart.setText("FAIL");
                BT_RESULT = false;
            }
        } else {
            //蓝牙是关闭状态
            Tools.logE("BT is OFF");
            updateUI(tvBT, "BT is OFF ");
        }
    }

    private void checkBTGPS() {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (adapter == null) {
            havaBT = false;
        }

        if (locationManager == null) {
            havaGPS = false;
        }
    }

    private void updateUI(final TextView view, final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                view.append(msg + "\n");
            }
        });
    }

    private void updateBtnUI(final Button view, final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                view.setText(msg);
            }
        });
    }

    private void setTestMode(boolean isTest) {
        if (mSharedPreferences == null){
            mSharedPreferences = this.getSharedPreferences("reboot",MODE_PRIVATE);
        }
        mSharedPreferences.edit().putBoolean("isTest",isTest).commit();
    }

    private boolean getTestMode(){
        if (mSharedPreferences == null){
            mSharedPreferences = this.getSharedPreferences("reboot",MODE_PRIVATE);
        }
        return mSharedPreferences.getBoolean("isTest",false);
    }

    public void stop(View view){
       setTestMode(false);
    }
}
